﻿using Newtonsoft.Json;
using System;
using System.Text;
using WeiXinEnterprise.SDK.Core;

namespace WeiXinEnterprise.SDK
{
    public class Token
    {
        /// <summary>
        /// 当前获取到的令牌
        /// </summary>
        public static Token CurrentToken { get; set; }

        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        [JsonProperty("expires_in")]
        public int ExpiresIn { get; set; }

        private DateTime createTokenTime = DateTime.Now;

        /// <summary>
        /// 到期时间(防止时间差，提前1分钟到期)
        /// </summary>
        /// <returns></returns>
        public DateTime TookenOverdueTime
        {
            get { return createTokenTime.AddSeconds(ExpiresIn - 60); }
        }

        private static string _mCorpID;

        public static string CorpID
        {
            get
            {
                if (string.IsNullOrEmpty(_mCorpID))
                    throw new NullReferenceException();
                return _mCorpID;
            }
        }

        private static string _mSecret;

        public static string Secret
        {
            get
            {
                if (string.IsNullOrEmpty(_mSecret))
                    throw new NullReferenceException();
                return _mSecret;
            }
        }

        /// <summary>
        /// 必须先调用该方法设置KEY
        /// </summary>
        /// <param name="CorpID">企业ID</param>
        /// <param name="Secret">管理员组ID</param>
        public static void SetKey(string CorpID, string Secret)
        {
            if (string.IsNullOrEmpty(CorpID) || string.IsNullOrEmpty(Secret))
                throw new ArgumentNullException();

            _mCorpID = CorpID;
            _mSecret = Secret;
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        public static void Renovate()
        {
            if (CurrentToken == null)
            {
                GetNewToken();
            }
            Token.CurrentToken.createTokenTime = DateTime.Now;
        }

        public static bool IsTimeOut()
        {
            if (CurrentToken == null)
            {
                GetNewToken();
            }
            return DateTime.Now >= Token.CurrentToken.TookenOverdueTime;
        }

        /// <summary>
        /// 获取企业号Token
        /// </summary>
        public static Token GetNewToken()
        {
            string strulr = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
            
            HttpHelper http = new HttpHelper();

            string respone = http.Get(string.Format(strulr, CorpID, Secret), Encoding.UTF8);

            var token = JsonConvert.DeserializeObject<Token>(respone);

            Token.CurrentToken = token;

            return token;
        }

        public static string GetToken()
        {
            if (CurrentToken == null)
            {
                GetNewToken();
            }
            return CurrentToken.AccessToken;
        }
    }
}
